package com.appjishu.web.controller;


import cn.hutool.http.server.HttpServerRequest;
import com.appjishu.passport.annotation.AuthController;
import com.appjishu.passport.intercepter.LoginInterceptor;
import com.appjishu.web.biz.service.UserService;
import com.appjishu.web.model.User;
import com.appjishu.web.util.MD5Util;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RequestMapping("user")
@Controller
@CrossOrigin
@AuthController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/changePassword")
    @ResponseBody
    public void changePassword(String password) {
        String newPassword = MD5Util.md5(password);
        Long userId = LoginInterceptor.getUserId();
        userService.changePassword(newPassword, userId);
    }

    @RequestMapping(value = "import", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String importExcelData(@RequestParam("file") MultipartFile file) {
        try {
            // 调用Service类的方法进行Excel导入
//            userService.importExcelData(file.getInputStream());
            userService.importExcelDataNew(file.getInputStream());
            return "数据导入成功！";
        } catch (Exception e) {
            e.printStackTrace();
            return "数据导入失败！";
        }
    }

    @RequestMapping(value = "/loginFormationOld", method = RequestMethod.GET, produces = {"application/json;" +
            "charset=UTF-8"})
    @ResponseBody
    public User importLoginFormationOld(@RequestParam("type") int type, HttpServerRequest request) {
        Long userId = LoginInterceptor.getUserId();
        User user = userService.selectAll(userId);
        User targetUser = new User();
        BeanUtils.copyProperties(user, targetUser);
        //登录
        if (type == 0) {
            //设置用户的登录时间
            Timestamp loginTime = new Timestamp(System.currentTimeMillis());
            Long onlineTimes = user.getOnlineTimes();
            if (onlineTimes == null) {
                onlineTimes = 0L;
            }
            //设置用户型号等信息
            String header = request.getHeader("User-Agent");
            // 定义正则表达式模式，匹配括号内的内容
            Pattern pattern = Pattern.compile("\\((.*?)\\)");
            Matcher matcher = pattern.matcher(header);
            String deviceType;
            if (matcher.find()) {
                // 提取第一个括号内的内容
                deviceType = matcher.group(1);
            } else {
                deviceType = "未知设备";
            }
            onlineTimes = onlineTimes + 1;
            userService.setLoginInformation(userId, loginTime, onlineTimes, deviceType);
            targetUser.setLoginTime(loginTime);
            targetUser.setOnlineTimes(onlineTimes);
            targetUser.setDeviceType(deviceType);
        } else {
            //设置用户离线时间
            Timestamp downlineTime = new Timestamp(System.currentTimeMillis());
            Long duration = downlineTime.getTime() - user.getLoginTime().getTime();
            Long allDuration = user.getAllDuration();
            //设置用户累计在线时长
            if (allDuration == null) {
                allDuration = 0L;
            }
            allDuration += duration;
            userService.setDownLineInformation(userId, downlineTime, duration, allDuration);
            targetUser.setDownlineTime(downlineTime);
            targetUser.setDuration(duration);
            targetUser.setDuration(allDuration);
        }
        return targetUser;
    }

    @RequestMapping(value = "/loginFormation", method = RequestMethod.GET, produces = {"application/json;" +
            "charset=UTF-8"})
    @ResponseBody
    public User importLoginFormation(HttpServletRequest request) {
        Long userId = LoginInterceptor.getUserId();
        User user = userService.selectAll(userId);
        User targetUser = new User();
        BeanUtils.copyProperties(user, targetUser);
        //登录
        //设置用户的登录时间
        Timestamp loginTime = new Timestamp(System.currentTimeMillis());
        Long onlineTimes = user.getOnlineTimes();
        if (onlineTimes == null) {
            onlineTimes = 0L;
        }
        //设置用户型号等信息
        String header = request.getHeader("User-Agent");
        // 定义正则表达式模式，匹配括号内的内容
        Pattern pattern = Pattern.compile("\\((.*?)\\)");
        Matcher matcher = pattern.matcher(header);
        String deviceType;
        if (matcher.find()) {
            // 提取第一个括号内的内容
            deviceType = matcher.group(1);
            int firstSemicolonIndex = deviceType.indexOf(';');
            if (firstSemicolonIndex != -1) {
                deviceType = deviceType.substring(0, firstSemicolonIndex);
            }
        } else {
            deviceType = "未知设备";
        }
        onlineTimes = onlineTimes + 1;
        targetUser.setLoginTime(loginTime);
        targetUser.setOnlineTimes(onlineTimes);
        targetUser.setDeviceType(deviceType);

        //设置用户离线时间
        Random random = new Random();
        int randomValue = random.nextInt(5400000 - 2400000 + 1) + 2400000;
        long downlineTimeMS = loginTime.getTime() + randomValue;
        Timestamp downlineTime = new Timestamp(downlineTimeMS);
        Long duration = downlineTime.getTime() - loginTime.getTime();
        Long allDuration = user.getAllDuration();
        //设置用户累计在线时长
        if (allDuration == null) {
            allDuration = 0L;
        }
        allDuration += duration;
        userService.setLoginDownInformation(userId, loginTime, onlineTimes, deviceType, downlineTime, duration,
                allDuration);
        if (user.getDownlineTime() != null && user.getDownlineTime().getTime() <= loginTime.getTime()) {
            userService.setUserInformation(userId, loginTime, downlineTime, deviceType, duration);
        }
        targetUser.setDownlineTime(downlineTime);
        targetUser.setDuration(duration);
        targetUser.setAllDuration(allDuration);
        return targetUser;
    }

}
